local hx__yice = fk.CreateSkill {
  name = "hx__yice",
}

local updataXianfu = function (room, player, target)
  local mark = player:getTableMark("hx__ximing")
  table.insertIfNeed(mark[2], target.id)
  room:setPlayerMark(player, "hx__ximing", mark)
  local names = table.map(mark[2], function(pid) return Fk:translate(room:getPlayerById(pid).general) end)
  room:setPlayerMark(player, "@hx__ximing", table.concat(names, ","))
end

hx__yice:addEffect(fk.Damaged, {
  name = "hx__yice",
  anim_type = "masochism",
  events = {fk.Damaged},
  trigger_times = function(self, event, target, player, data)
    return data.damage
  end,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(hx__yice.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local judge = {
      who = player,
      reason = hx__yice.name,
      pattern = ".|.|^nosuit",
    }
    room:judge(judge)
    if judge.card.color == Card.Red then
      local judge = {
        who = player,
        reason = hx__yice.name,
        pattern = ".|.|^nosuit",
      }
      room:judge(judge)
      if judge.card.color == Card.Red then
        local tos = room:askToChoosePlayers(player, {
          targets = room:getAlivePlayers(),
          min_num = 1,
          max_num = 1,
          prompt = "#hx__yice-draw",
          cancelable = false,
          skill_name = hx__yice.name,
        })
        local to = tos[1]
        local num = 1
        local mark = player:getTableMark("hx__ximing")
        if #mark > 0 and table.contains(mark[1], to.id) then
          num = 2
          updataXianfu (room, player, to)
        end
        to:drawCards(num, hx__yice.name)
      elseif judge.card.color == Card.Black then
        local targets = table.filter(room.alive_players, function(p) return not p:isAllNude() end)
        if #targets == 0 then return end
        local tos = room:askToChoosePlayers(player, {
          targets = targets,
          min_num = 1,
          max_num = 1,
          prompt = "#hx__yice-discard",
          cancelable = false,
          skill_name = hx__yice.name,
        })
        local to = tos[1]
        local card = room:askToChooseCard(player, {
          target = to,
          skill_name = hx__yice.name,
          flag = "hej",
        })
        room:obtainCard(player,card,false, fk.ReasonPrey)
      end
    elseif judge.card.color == Card.Black then
      player:drawCards(2, hx__yice.name)
      if player.dead or player:isKongcheng() then return end
      room:askToYiji(player, {
        cards = player:getCardIds("h"),
        min_num = 0,
        max_num = 2,
        skill_name = hx__yice.name,
      })
    end
  end,
})

return hx__yice